package workspace.teaweb.base.exception;



import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import workspace.teaweb.base.response.JsonResult;
import workspace.teaweb.base.response.StatusCode;

import javax.validation.ConstraintViolationException;
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandleServiceException(ServiceException ex) {
        log.error("ServiceException:" + ex.getStatusCode().getMessage());
        return new JsonResult(ex.getStatusCode());
    }
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {
        String message = ex.getMessage();
        log.error("IllegalArgumentException: " + message);

        return new JsonResult(StatusCode.OPERATION_FAILED, message);
    }
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex) {
        String message = ex.getMessage();
        log.error("RuntimeException: " + message);

        return new JsonResult(StatusCode.OPERATION_FAILED, message);
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        //Validation中,验证POJO类型参数获取提示消息使用: ex.getFieldError().getDefaultMessage() 方法.
        String message = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException: " + message);

        return new JsonResult(StatusCode.VALIDATED_ERROR, message);
    }


}